﻿using AppFramework.Logger;
using PerpheralDevice;
using PerpheralDevice.IRepository;
using System.Reflection;
using System.Runtime.CompilerServices;

namespace AppMachine.Domain.LogicCom;

/// <summary>
/// 应用逻辑组件基类
/// </summary>
public abstract class AppCom {
    protected readonly ILogger _logger = ILogger.Default;
    public AppCom() { }
    public AppCom(IPerpDevRepository perpDevRepository, IComConfig comConfig, IComRepository comRepository) : this() {
        this.mfIPerpDevRepository = perpDevRepository;
        this.mfIComRepository = comRepository;
        this.ComConfig = comConfig;
    }

    /// <summary>
    /// 应用组件ID
    /// </summary>
    public string ComID =>this.ComConfig.ComID;
    public string TagName => this.ComConfig.TagName;
    /// <summary>
    /// 设置应用组件的标签
    /// </summary>
    /// <param name="tagName">标签</param>
    /// <returns></returns>
    public AppCom TagNameSet(string tagName) {
        (this.ComConfig as AppComConfig)!.TagName = tagName.Replace(" ", "");
        return this;
    }
    /// <summary>
    /// 应用组件配置
    /// </summary>
    public IComConfig ComConfig { get; protected set; }

    protected IComRepository mfIComRepository;
    protected IPerpDevRepository mfIPerpDevRepository;

    private readonly List<object> OnStatusChangedActionList = [];
    /// <summary>
    /// 组件的状态发生变化
    /// </summary>
    /// <returns></returns>
    protected AppCom OnStatusChangedRaise() {
        Queue<object> tempQueue = new (this.OnStatusChangedActionList);
        while (tempQueue.Count > 0) {
            object tempAction = tempQueue.Dequeue();
            Task.Factory.StartNew((action) => {
                MethodInfo? tempMethodInfo = action?.GetType().GetMethod("Invoke");
                tempMethodInfo?.Invoke(action, [this]);
            }, tempAction);
        }
        return this;
    }
    /// <summary>
    /// 注册事件委托 组件的状态发生变化
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="action"></param>
    [MethodImpl(MethodImplOptions.Synchronized)]
    public T Add<T>(Action<T> action) where T : AppCom {
        if (!this.OnStatusChangedActionList.Contains(action)) {
            this.OnStatusChangedActionList.Add(action);
        }

        return this as T;
    }

    /// <summary>
    /// 取消事件委托 组件的状态发生变化
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="action"></param>
    [MethodImpl(MethodImplOptions.Synchronized)]
    public T Rem<T>(Action<T> action) where T : AppCom {
        if (this.OnStatusChangedActionList.Contains(action)) {
            this.OnStatusChangedActionList.Remove(action);
        }

        return this as T;
    }

    public virtual AppCom Save() {
        (this.ComConfig as AppComConfig)!.Save();
        return this;
    }

}
